package com.jackchong.utils;

import android.graphics.Rect;
import android.view.View;
import android.widget.GridLayout;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 作者: jack(黄冲)
 * 邮箱: 907755845@qq.com
 * create on 2018/12/29 14:17
 */

public class GridItemDecoration extends RecyclerView.ItemDecoration{

    private int left, top, right, bottom;
    private boolean stroke;

    public GridItemDecoration(boolean stroke, int spacing) {
        this.stroke = stroke;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        int spanCount = 1;

        if (parent.getLayoutManager() instanceof GridLayoutManager){
            GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
            spanCount = layoutManager.getSpanCount();
        }


        int childAdapterPosition = parent.getChildAdapterPosition(view);
        int row = childAdapterPosition % spanCount;
        int column = childAdapterPosition / spanCount;

        int firstPosition = 0;
        int lastPosition = -1;
        if (parent.getAdapter() != null && parent.getAdapter().getItemCount() > 0){
            lastPosition = parent.getAdapter().getItemCount();
        }
        if (lastPosition != -1 && parent.getChildAdapterPosition(view) == lastPosition -1) {
            outRect.bottom = top;
        }


        if (row == 0 && stroke) {
            outRect.left = left;
        }else if (row == spanCount - 1 && stroke){
            outRect.right = right;
        }else {
            outRect.left = left;
        }

        if (column == 0 && stroke){
            outRect.top = top;
        }else if (column == lastPosition - 1 && stroke){
            outRect.bottom = bottom;
        }else {
            outRect.top = top;
        }
    }
}
